package com.sxkf.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxkf.template.entity.Product;
import com.sxkf.template.entity.ProductSpec;
import com.sxkf.template.entity.Store;
import com.sxkf.template.mapper.ProductMapper;
import com.sxkf.template.mapper.ProductSpecMapper;
import com.sxkf.template.mapper.StoreMapper;
import com.sxkf.template.vo.response.cart.QueryUserCartVO;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.template.mapper.ShoppingCartMapper;
import com.sxkf.template.entity.ShoppingCart;
import com.sxkf.template.service.ShoppingCartService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService{
    @Resource
    private StoreMapper storeMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductSpecMapper productSpecMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public List<Store> listUserCart(String userId) {
        List<QueryUserCartVO> userCartVOS = baseMapper.listUserCartVO(userId);
        Map<String, List<QueryUserCartVO>> carMap = userCartVOS.stream().collect(Collectors.groupingBy(QueryUserCartVO::getStoreId));
        List<Store> stores = new ArrayList<>();
        carMap.forEach((key,value)-> {
            Store store = storeMapper.selectById(key);
            store.setQueryUserCartVOS(value);
            stores.add(store);
        });
        return stores;
    }

    @Override
    public void add(ShoppingCart shoppingCart) {
        Product product = productMapper.selectById(shoppingCart.getProductId());
        if (CheckEmptyUtil.isEmpty(product)) {
            throw new SxkfException(500, "商品不存在");
        }
        ProductSpec productSpec = productSpecMapper.selectById(shoppingCart.getProductSpecId());
        if (productSpec.getStock() <= 0) {
            throw new SxkfException(500, "商品库存不足");
        }
        ShoppingCart one = getOne(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getProductSpecId, shoppingCart.getProductSpecId())
                .eq(ShoppingCart::getStoreId, shoppingCart.getStoreId())
                .eq(ShoppingCart::getUserId, shoppingCart.getUserId())
                .eq(ShoppingCart::getProductId, shoppingCart.getProductId())
        );
        if (one == null){
            save(shoppingCart);
        }else {
            one.setCount(one.getCount()+shoppingCart.getCount());
            updateById(one);
        }
    }
}
